<template>
    <el-menu
        class="ym-menu"
        :collapse="userStore.menuIsCollapse"
        router
        unique-opened
        :default-active="menuIndex"
        @open="handleOpen"
        @close="handleClose">
        <template v-for="(menuRouter, index) in menuRouters" :key="index">
            <!-- 一级菜单，只有一个子路由（index） -->
            <el-menu-item
                v-if="menuRouter.children && menuRouter.children.length == 1"
                :index="menuRouter.path + '/' + menuRouter.children[0].path">
                <el-icon>
                    <component :is="menuRouter.meta?.icon" />
                </el-icon>
                <span>{{ menuRouter.meta?.title }}</span>
            </el-menu-item>
            <!-- 二级菜单，有多个子路由 -->
            <el-sub-menu v-else :index="menuRouter.path">
                <template #title>
                    <el-icon>
                        <component :is="menuRouter.meta?.icon" />
                    </el-icon>
                    <span>{{ menuRouter.meta?.title }}</span>
                </template>
                <el-menu-item-group>
                    <template v-for="(subItem, subIndex) in menuRouter.children" :key="subIndex">
                        <el-menu-item :index="menuRouter.path + '/' + subItem.path">{{ subItem.meta?.title }}</el-menu-item>
                    </template>
                </el-menu-item-group>
            </el-sub-menu>
        </template>
    </el-menu>
</template>
<script setup lang="ts">
    import { computed, onMounted, ref } from 'vue'
    import { useRouter } from 'vue-router'
    import { useUserStore } from '@/stores/user'
    const userStore = useUserStore()
    const isCollapse = ref(false)
    const router = useRouter()
    const menuRouters = ref<any>([])
    // const menuRouters = router.options.routes.filter((item) => {
    //     return item.meta?.isShowMenu
    // })
    // const menuRouters = userStore.menus?.filter((item) => {
    //     return !item.is_hidden
    // })
    const menuIndex = computed(() => router.currentRoute.value.path)
    onMounted(() => {
        if (import.meta.env.VITE_ROUTE_MODE === 'dynamic' && userStore.menus) {
            menuRouters.value = userStore.menus?.filter((item) => {
                return !item.is_hidden
            })
        } else {
            menuRouters.value = router.options.routes.filter((item) => {
                return item.meta?.isShowMenu
            })
        }
    })

    const handleOpen = (key: string, keyPath: string[]) => {
        // console.log(key, keyPath)
    }
    const handleClose = (key: string, keyPath: string[]) => {
        // console.log(key, keyPath)
    }
</script>

<style scoped>
    .ym-menu:not(.el-menu--collapse) {
        width: var(--ym-aside-width, 200px);
    }
</style>
